package cn.wolfcode.mq;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author LuoRis
 * @date 2021/03/08 20:40
 * @description TODO
 */

@Slf4j
@Component
@RocketMQMessageListener(
        topic = MQConstant.ORDER_PAY_TIMEOUT_TOPIC,
        consumerGroup = "MQOrderTimeOutListener"
)
public class MQOrderTimeOutListener implements RocketMQListener<OrderMQResult> {
    @Autowired
    private IOrderInfoService orderInfoService;

   /* @Autowired
    private StringRedisTemplate redisTemplate;*/

    @Autowired
    private ISeckillProductService seckillProductService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("-----进入延时消费队列-----");
        //	获取订单编号
        String orderNo = orderMQResult.getOrderNo();
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        //	判断是否支付(订单状态)
        if (OrderInfo.STATUS_ARREARAGE.equals(orderInfo.getStatus())){
            //	正在取消的过程中 (另外一个线程支付了  用户手动取消)
            int count = orderInfoService.updateCancleStatus(orderNo,OrderInfo.STATUS_TIMEOUT);
            if (count==0){
                throw new BusinessException(SeckillCodeMsg.CANCEL_ORDER_ERROR);
            }
            //	修改订单状态
            //orderInfo.setStatus(OrderInfo.STATUS_TIMEOUT);
            orderInfoService.updateCancleStatus(orderNo,OrderInfo.STATUS_TIMEOUT);
            //	回补真实库存
            seckillProductService.incrCount(orderMQResult.getSeckillId());
            //	回补预库存 seckillProductStock:time   seckillId   stockcount
            //  不能直接进行
            //  直接把数据库的真实库存查询出来
            //int productCount = seckillProductService.selectProductCount(orderInfo.getSeckillId());
            //  然后设置到redis当中
            //redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(orderInfo.getSeckillTime() + ""),orderInfo.getSeckillId()+"",productCount+"");
            //	修改本地标识
            rocketMQTemplate.syncSend(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderMQResult.getSeckillId());
        }

    }
}
